<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>拖动模态框</title>
    <style>
      .mo {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0.3;
        background-color: black;
      }
      .login {
        display: none;
        position: absolute;
        top: 50%;
        left: 50%;
        width: 300px;
        height: 200px;
        /*margin-left: -150px;*/
        /*margin-top: -10px;*/
        transform: translate(-150px, -10px);
        box-shadow: 0 0 5px 1px black;
        background-color: white;
        vertical-align: center;
        text-align: center;
        cursor: move;
      }
      .login .user,
      .password {
        margin-top: 30px;
      }
      input[value="登录"] {
        margin-top: 30px;
      }
      .login .close {
        position: absolute;
        top: -18px;
        left: 268px;
        width: 40px;
        height: 40px;
        border: 1px solid black;
        background-color: white;
        border-radius: 20px;
        text-align: center;
        line-height: 40px;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div class="hint">点击弹出登录框</div>
    <div class="mo"></div>
    <div class="login">
      <div class="close">关闭</div>
      <div class="user">用户名<input type="text" /></div>
      <div class="password">密码<input type="password" /></div>
      <input type="submit" value="登录" />
    </div>
    <script>
      var hint = document.querySelector(".hint");
      var mo = document.querySelector(".mo");
      var box = document.querySelector(".login");
      var close = document.querySelector(".close");
      hint.addEventListener("click", function () {
        mo.style.display = "block";
        box.style.display = "block";
      });
      close.addEventListener("click", function () {
        mo.style.display = "none";
        box.style.display = "none";
      });
      //拖拽实现
      box.addEventListener("mousedown", function (e) {
        var x = e.clientX - this.offsetLeft,
          y = e.clientY - this.offsetTop;
        var move = function (e) {
          box.style.left = e.clientX - x + "px";
          box.style.top = e.clientY - y + "px";
          console.log(e.clientX, x, e.clientY, y);
        };
        document.addEventListener("mousemove", move);
        document.addEventListener("mouseup", function () {
          this.removeEventListener("mousemove", move);
        });
      });
    </script>
  </body>
</html>
